package com.woohua.thread.lockreadwrite;

import java.util.Hashtable;
import java.util.Map;

/***
 * @title CacheManager
 * @description
 * @author woo hua
 * @version 1.0.0
 * @create 2023/3/16 17:08
 **/
public class CacheManager<K, V> {

    private Map<Integer, Cache<K, V>> cacheMap = new Hashtable<Integer, Cache<K, V>>();

    /**
     * 私有构造器
     */
    private CacheManager() {
    }

    private static volatile CacheManager cacheManager;


    public static CacheManager getInstance() {
        if (null == cacheManager) {
            synchronized (CacheManager.class) {
                if (null == cacheManager) {
                    cacheManager = new CacheManager();
                }
            }
        }
        return cacheManager;
    }

    /**
     * 注册缓存
     *
     * @param cacheKey 缓存Key
     * @param cache
     */
    public void registerCache(Integer cacheKey, Cache<K, V> cache) {
        cache._init();
        cacheMap.put(cacheKey, cache);
    }

    /**
     * 从指定缓存中获取数据
     *
     * @param cacheKey 缓存Key
     * @param key
     * @return
     */
    public V getValue(Integer cacheKey, K key) {
        Cache<K, V> cache = cacheMap.get(cacheKey);
        return cache.get(key);
    }

    /**
     * 设置缓存
     *
     * @param cacheKey 缓存Key
     * @param key
     * @param value
     */
    public void put(Integer cacheKey, K key, V value) {
        Cache<K, V> cache = cacheMap.get(cacheKey);
        cache.put(key, value);
    }

    /**
     * 从指定缓存中删除数据
     *
     * @param cacheKey 缓存Key
     * @param key
     * @return
     */
    public V remove(Integer cacheKey, K key) {
        Cache<K, V> cache = cacheMap.get(cacheKey);
        return cache.remove(key);
    }
}
